<template>
  <div class="h-full w-full">
    <SplitPanel v-show="!showForm" :style="{ 'flex-direction': 'row !important' }" class="user-page-box">
      <template #left-content>
        <div class="flex justify-between flex-col h-full">
          <div class="title">全部分类</div>
            <div class="flex justify-between flex-col h-full">
              <Tree
                v-model:expandedKeys="state.expandedKeys"
                auto-expand-parent
                :tree-data="state.dataTree"             
                :onSelect="onTreeSelect"
              >
              </Tree>
            </div>      
        </div>
      </template>
      <template #right-content>
        <a-card>
            <a-button type="primary" @click="newFlow()">
              <PlusOutlined />新建
            </a-button>
          <div v-for="(item, index) in flowList" :key="index" class="custom-tab-block">
            <template v-if="currentFlowSortId === item.sortId || currentFlowSortId === -1">
              <p class="title">{{ item.sortName }}</p>
              <a-row :gutter="20" class="custom-tab-block-content">
                <a-col
                  :sm="8"
                  :lg="6"
                  :xl="4"
                  v-for="(f, findex) in getFlowTag(item.sortId)"
                  :key="f.procDefId"
                >
                  <div class="custom-tab-block-item" >
                    <div
                      class="img"
                      
                    >
                    <img v-if="f.picture" style="width: 100%; height: 100%;"  :src="f.picture"  />
                    <img v-else style="width: 100%; height: 100%;"  src="/src/assets/images/fawen.png"  />
                    </div>
                    <span @click="startTask(f.procDefId, f.name)" class="name">{{ f.procName }}</span>  <StarOutlined v-if="!f.isCommonFlow" :style="{color:'#52c41a'}"  @click="handleIconClick(f)" />      
                    <StarFilled v-if="f.isCommonFlow"  :style="{color:'#52c41a'}"  />
                         
                  </div>
                </a-col>
              </a-row>           
            </template>
          </div>
        </a-card>
        <a-config-provider :theme="{
          algorithm: theme.defaultAlgorithm,
          token: {
            colorBgBase: '#FFF',
          },
        }">

          <a-modal v-if="addForm" @cancel="handleDrawClose" @ok="designViewInit" class="formDrawer" :closable="false"
            title="新建连接流" width="50%" height v-model:open="addForm" placement="bottom" destroyOnClose>
            <a-form style="height: 30vh;" ref="flowInfoRef" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"
              :model="procInfo.procInfo">
              <a-row :gutter="24" style="margin-left: 0px;margin-right:50px;margin-top: 20px;">
                <a-col :span="24">
                  <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
                    <a-input v-model:value="procInfo.procInfo.name"></a-input>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="24">
                  <a-form-item label="编码" name="name" :rules="[{ required: true, message: '请输入编码!' }]">
                    <a-input v-model:value="procInfo.procInfo.name"></a-input>
                  </a-form-item>
                </a-col> -->
                <a-col :span="24">
                  <a-form-item label="状态" name="proc_type" :rules="[{ required: true }]">
                    <a-switch v-model:checked="procInfo.procInfo.proc_type" checked-children="开" un-checked-children="关" />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="类型" name="sortId" :rules="[{ required: true, message: '请选择类型!' }]">
                    <a-radio-group v-model:value="procInfo.procInfo.sortId" >
                      <a-radio value="activeTrigger">主动触发</a-radio>
                      <a-radio value="timedTasks">定时任务</a-radio>
                      <a-radio value="listeners">监听事件</a-radio>
                      <a-radio value="webhook">Webhook</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-modal>

        </a-config-provider>
      </template>
    </SplitPanel>
    <div v-if="showForm" class="formDrawer bg-white overflow-auto p-[14px]" :closable="false" width="100%" height="90%"
       placement="bottom" :keyboard="false" destroyOnClose>
      <DesignView @closeDrawer="handleDrawClose" :xml="designXML" :taskList="taskList" :connectionList="connectionList">
      </DesignView>
    </div>
  </div>
  </template>
  
  <script setup lang="ts">
    import { ref, reactive, h, computed } from 'vue';
    import { Tree, Modal, Alert} from 'ant-design-vue';
    import { type TreeDataItem } from '@/core/permission/utils';
    import { message } from 'ant-design-vue';
    import { getCommonFlowList } from '@/api/flow/index';
    import { getFlowSortList } from '@/api/flow/sort';
    import {
  getFlowList, deleteFlow, deploymentXML, getTaskListWithProcessKey, getBusinessMethodListByProcessDefinitionId,
  getConnectionListByProcessKey, getGateWayListByProcDefKey
} from '@/api/flow/index';
    import { getFormJSON } from '@/api/flow/index';
    import { flatTree } from '@/core/permission/utils';
     import { formatFlowSortTree } from '@/views/flow/category/columns';
     import { cloneDeep } from 'lodash-es';
     import { theme } from 'ant-design-vue';
     import { itemReadOnly } from '@/utils/common';
     import {
  DeleteOutlined,
  SettingOutlined,
  WalletOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue';
import { processInfo } from '@/store/modules/processInfo';
import { getFlowParamsTemplate, getTemporaryVariable, getTimeoutEntityList } from '@/api/deployment/index';
import { taskAttr } from '@/store/modules/taskAttr';
import { gateWayAttr } from '@/store/modules/gateWay';
import { businessMethods } from '@/store/modules/businessMethod';
import DesignView from "@/components/design/index.vue";
import type { FormInstance } from 'ant-design-vue';
import { getProcessProperties } from '@/api/deployment/index';
     
  import {
    StarOutlined,StarFilled
  } from '@ant-design/icons-vue';
  import { color } from 'echarts';
  
  
    defineOptions({
      name: 'connector',
    });
  
     interface State {
      expandedKeys:any;
      dataTree: TreeDataItem[];
    }
  
   const state = reactive<State>({
      expandedKeys:"",
      dataTree: [],
    });
  
    const flowList: any = ref([]);
  
    const flowSortData: any = ref([]);
    const designXML = ref<any>(null);
    //加载流程类别数据
    const nodeFormOptions = ref<[{}]>();
    const taskList = ref<any>(null);
    const connectionList = ref<any>(null);
    const gateWayList = ref<any>(null);
    const flowInfoRef = ref<FormInstance>();

    const formId = ref('');
    const tabList = ref<API.FlowSortListResultItem[]>();
    const activeKey = ref();
    const choosedSort = ref('');
    //节点列表
    const taskAttrStore = taskAttr();
    //网关列表
    const gateWayStore = gateWayAttr();
    //业务方法列表
    const businessMethodsStore = businessMethods();

    const showForm = ref(false);
    const addForm = ref(false);
    const handleDrawClose = () => {
      procInfo.setStateData("name", "");
      procInfo.setStateData("sortId", "");
      procInfo.setStateData("id", "");
      showForm.value = false;
      addForm.value = false;
    };
    const designViewInit = () => {
      console.log(procInfo.procInfo, "procInfo.procInfo11111111111111111111111")
      addForm.value=false;
      showForm.value = true;
    };
    const procInfo = processInfo();

    // 编辑
    const handleEdit = async (row) => {
      const res = await deploymentXML({ deploymentId: row.procDefId });
      if (res) {
        designXML.value = res;
      }
      procInfo.setStateData("id", row.procDefId);
      procInfo.setStateData("name", row.procName);
      procInfo.setStateData("sortId", row.flowSort);
      const data = await getTaskListWithProcessKey({ PROCESS_KEY: row.procDefId });
      if (data.error == 200) {
        const taskInfo = data.result.map((item) => {
          if (item.TASK_RUN_DATA != "") {
            item.TASK_RUN_DATA = JSON.parse(item.TASK_RUN_DATA)
          }
          if (item.TASK_NODE_FORM_DATA_POWER != "") {
            item.TASK_NODE_FORM_DATA_POWER = JSON.parse(item.TASK_NODE_FORM_DATA_POWER)
          }
          return item;
        });
        taskList.value = taskInfo;
      }
      const proper = await getProcessProperties({ id: row.procDefId });
      if (proper.error == "200") {
        procInfo.setStateData("form_type", proper.result.form_type);
        procInfo.setStateData("form_url", proper.result.form_url);
        procInfo.setStateData("formId", proper.result.formId);
        procInfo.setStateData("picture", proper.result.picture);
        procInfo.setStateData("startPower", proper.result.startPower);
        procInfo.setStateData("titleModel", proper.result.titleModel);
        procInfo.setStateData("powerData", JSON.parse(proper.result.powerData));
      }
      //todo 需要和tasklist合并 ,要考虑是脚本的情况，目前只是一种情况
      const connectData = await getConnectionListByProcessKey({ PROCESS_KEY: row.procDefId });
      if (connectData.error == 200) {
        if (connectData.result.length === 0) {
          // const blankConnection = createConnection();
          //connectionList.value=blankConnection;
          connectionList.value = [];
        }
        else {
          const connectionsInfo = connectData.result.map((item) => {
            if (item.expressBody != "") {
              item.expressBody = JSON.parse(item.expressBody)
            }
            return item;
          });
          connectionList.value = connectionsInfo;
        }

        //
      }

      //网关
      const gateWays = await getGateWayListByProcDefKey({ PROC_DEF_ID: row.procDefId });
      if (gateWays.error == 200) {
        if (gateWays.result.length === 0) {
          gateWayList.value = [];
        }
        else {
          gateWayList.value = gateWays.result;
        }
        gateWayStore.setStateData(gateWayList);
      }
      //业务方法
      const bizMethods = await getBusinessMethodListByProcessDefinitionId({ PROC_DEF_ID: row.procDefId });
      if (bizMethods.status === '200') {
        let bizlist;
        if (bizMethods.result.length === 0) {
          bizlist = [];
        }
        else {
          bizlist = bizMethods.result;
        }
        businessMethodsStore.setStateData(bizlist);
      }


      procInfo.procVariable = [];
      const paramRes = await getFlowParamsTemplate();
      if (paramRes.status === "200") {
        const paramTree = formatFormTree(paramRes.result.filter((item => item.paramClass == "0")), "0");
        procInfo.setVariable(paramTree);
      }
      const temporaryVariableRes = await getTemporaryVariable({ PROC_DEF_ID: row.procDefId });
      if (temporaryVariableRes.status === "200") {
        procInfo.setVariable(temporaryVariableRes.result);
      }
      console.log(procInfo, "procInfo111111111111")
      const timeoutRes = await getTimeoutEntityList({ proc_def_id: row.procDefId });
      if (timeoutRes.status === "200") {
        procInfo.setStateData('timeoutData', timeoutRes.result);
      }
      if (res && data) {
        showForm.value = true;
      }
    };
    // 新增
    const newFlow = () => {
      taskList.value = [];
      connectionList.value = [];
      businessMethodsStore.$reset();
      gateWayStore.$reset();
      procInfo.setStateData("id", "");
      procInfo.setStateData("sortId", '1');
      designXML.value = null;
      addForm.value = true;
    };

    const formatFormTree = (
      datas: [],
      parentNo: number | string = 0,
      keyPath: (string | number)[] = [],
    ): TreeDataItem[] => {
      return datas
        .filter((item) => item.parentId === parentNo)
        .map((item) => {
          const _keyPath = keyPath.concat(parentNo || []);
          const arr = formatFormTree(datas, item.id, _keyPath);
          return Object.assign(item, {
            title: item.name,
            key: item.id,
            label: item.name,
            value: item.id,
            children: arr.length ? arr : [],
          });
        });
    };
    const handledeleteFlow = async (procKey) => {
      await deleteFlow(procKey);
    };

    const transformTreeData = (data: any[]): any[] => {
      return data.map(node => ({
        value: node.sortId,
        label: node.sortName,
        title: node.sortName,
        children: node.children ? transformTreeData(node.children) : undefined,
      }));
    };

   
    const loadComData = async () => {
      const data = await getCommonFlowList();
      flowList.value = data.result?.flowList ?? [];
    };
    loadComData();
  
     // 获取分类数据
    const loadSortList = async () => {   
      const data = await getFlowSortList();
      const flatTreeData = flatTree(data.result);    
      state.dataTree = formatFlowSortTree(cloneDeep(flatTreeData), 0);   
  
      flowSortData.value = data?.result ?? [];
      nodeFormOptions.value=transformTreeData(state.dataTree);
    };
    loadSortList();
  
   /**
       * 点击模版
       */
       const onTreeSelect = (selectkeys) => {
        state.expandedKeys = selectkeys;
        currentFlowSortId.value = selectkeys[0];
      //  dynamicTableInstance?.reload?.();
      };
  
    
  
    const currentFlowSortId = ref<number>(-1);
    const handleFlowSortChoose = (id) => {
      currentFlowSortId.value = id;
    };
   
  
    const getFlowTag = (id) => {
      const flowRows = flowList.value.filter((item) => item?.sortId === id);
      return flowRows && flowRows.length ? flowRows[0]?.flowList : [];
    };
  
    // 预览表单参数
    const previewFormObj = reactive<any>({
      itemList: [],
      formConf: {},
      dataJson: {},
    });
  
    // 流程参数
    const previewConfig = reactive({
      showDrawer:ref(false),
      form_url: '',
      form_type: '',
      processName: '',
      isDraft:ref(true),
      isStartProcess:ref(false),
      processKey: '',
      taskid: '',
      businessKey: '',
      procinstid: '',
      isCollected: ref(false),
      dataJson: {},
      
    });
  
    const showDrawer = ref(false);
   const handleIconClick = async(f) =>{    
       if(!f.isCommonFlow)
       {
         let upd :API.UserProcessDefine={
          processDefineId:f.procDefId,
         };
         const dr = await addUserProcessDefine(upd);
       }
       f.isCommonFlow = !f.isCommonFlow; 
  
   }
  
   const cancelIconClick = async(f) =>{         
        
         const dr = await deleteUserProcessDefine({processDefineId:f.procDefId});
       
  
   }
  
   
  
    // 开始流程
    const startTask = async (id, name) => {
      if (id == '') {
        message.error('没有找到流程processKey，请联系管理员');
        return;
      }
      previewConfig.taskid = "";     
      previewConfig.processName = name;
      previewConfig.processDefinitionId = id;
      const res: any = await getFormJSON({ processkey: id, taskid: '' });
      if (res.error == '200') {
        if (!res.result || Object.keys(res.result).length == 0) {
         // message.error('无数据');
         // return;
         showDrawer.value = true;
        }
        else{
          const mapJSON = JSON.parse(res.result.mapJson);
          previewConfig.processName = name;
          previewConfig.processDefinitionId = id;
          previewFormObj.itemList = itemReadOnly(mapJSON.list ?? [],res.result.dataPower=="" ? undefined: JSON.parse(res.result.dataPower?? []));
          console.log(previewFormObj,"previewFormObj11111")
          previewFormObj.formConf = mapJSON.config ?? {};
          previewConfig.form_url = res.result.form_url;
          previewConfig.form_type = res.result.form_type;
          showDrawer.value = true;
        }
        
        
      } else {
        message.error(res.result);
      }
    };
  
    // 关闭
    const handleCancel = () => {
      showDrawer.value = false;
      previewConfig.taskid='';
      previewConfig.processDefinitionId='';
    };
    
  </script>
  <style lang="less">
    .startFlowDrawer .ant-drawer-body {
      padding: 10px !important;
    }
  
    .startFlowDrawer :deep(.ant-drawer-header-title) {
      flex-direction: row-reverse;
    }
  </style>
  <style lang="less" scoped>
    @import '@/styles/navTheme.less';
    @classBacks: all-flow-container, com-box;
  
    .themeSetStyle(@classBacks, background-color, sec-back);
  
    .themeSetStyle(@classBacks, color, wb-text);
  
    .flow-start-container {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
    }
  
    .noBox {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100px;
      background: rgba(#000, 0.03);
      font-size: 14px;
    }
  
    .com-box {
      margin-bottom: 16px;
      padding: 10px 16px;
      background-color: #fff;
  
      &-title {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        font-size: 16px;
      }
  
      &-content {
        width: 100%;
        overflow: auto hidden;
        white-space: nowrap;
  
        &-item {
          display: inline-block;
          box-sizing: border-box;
          width: 250px;
          height: 100px;
          margin-right: 10px;
          margin-bottom: 10px;
          border-radius: 4px;
          color: #fff;
          font-size: 16px;
          line-height: 100px;
          text-align: center;
          cursor: pointer;
  
          &:last-of-type {
            margin-right: 0;
          }
  
          &:hover,
          &.is-active {
            box-shadow:
              0 2px 7px 0 rgb(0 0 0 / 32%),
              0 1px 4px 0 rgb(183 183 183 / 6%);
          }
        }
      }
    }
  
    .all-flow-container {
      display: flex;
      flex: 1;
      padding: 15px 20px;
      background-color: #fff;
  
      .custom-tab {
        flex-grow: 0;
        margin-right: 35px;
  
        .title {
          font-size: 16px;
          font-weight: 500;
        }
  
        .custom-tab-content {
          padding: 0;
          list-style-type: none;
  
          .custom-tab-item {
            min-width: 100px;
            height: 43px;
            border-bottom: 1px solid #e8e8e8;
            font-size: 14px;
            line-height: 43px;
            text-align: center;
            cursor: pointer;
  
            &.is-active {
              border-bottom: 2px solid #1890ff;
              color: #1890ff;
            }
          }
        }
      }
  
      .custom-tab-container {
        flex-grow: 1;
        overflow-y: auto;
  
        .custom-tab-block {
          box-sizing: border-box;
  
          .title {
            margin: 10px 0 20px;
            font-size: 16px;
            font-weight: 500;
            text-decoration: underline double #1890ff;
            text-decoration-thickness: initial;
          }
  
          .subtitle {
            font-size: 16px;
            font-weight: 500;
          }
  
          .custom-tab-block-content {
            box-sizing: border-box;
            width: 100%;
  
            .custom-tab-block-item {
              display: flex;
              box-sizing: border-box;
              align-items: center;
              height: 70px;
              margin-bottom: 20px;
              padding: 0 20px;
              border: 1px solid #dee0e3;
              border-radius: 6px;
              font-size: 15px;
              font-weight: 500;
              line-height: 70px;
              text-align: left;
              cursor: pointer;
  
              &:hover {
                border-color: #1890ff;
                color: #1890ff;
              }
  
              .img {
                display: inline-block;
                width: 34px;
                height: 34px;
                margin-right: 10px;
                border-radius: 4px;
                color: #fff;
                line-height: 34px;
                text-align: center;
                vertical-align: middle;
              }
  
              .name {
                display: inline-block;
                flex: 1;
                line-height: 18px;
                word-wrap: break-word;
                word-break: break-all;
              }
            }
          }
        }
      }
    }
  </style>
  
  <style lang="less" scoped>
    @import '@/styles/navTheme.less';
    @classBacks: theme-tab-container-flow;
    .customSetStyle(@classBacks, background-color, 'content-back');
  
    .theme-tab-container-flow {
      margin-bottom: 10px;
      padding: 10px 0 20px 16px;
      background-color: #fff;
  
      .noBox {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100px;
        background: rgba(#000, 0.03);
        font-size: 14px;
      }
  
      .card-box {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        width: calc(100vw - 280px);
        overflow: auto;
  
        .card-content {
          display: inline-block;
          box-sizing: border-box;
          width: 226px;
          height: 100px;
          border-radius: 4px;
          color: #fff;
          font-size: 16px;
          margin-right: 10px;
          line-height: 100px;
          text-align: center;
          cursor: pointer;
          flex-shrink:0;
  
          &:last-of-type {
            margin-right: 0;
          }
  
          &:hover,
          &.is-active {
            box-shadow:
              0 2px 7px 0 rgb(0 0 0 / 32%),
              0 1px 4px 0 rgb(183 183 183 / 6%);
          }
        }
      }
    }
  </style>
  <style lang="less" scoped>
      @import '@/styles/navTheme.less';
      @classBacks: user-page-box;
      .customSetStyle(@classBacks, background-color, 'content-back-user');
    
      :deep(.ant-tree) {
        flex: 1;
      }
    </style>
  